package com.second.app.thread.线程基础.day07.线程通信.唤醒通知;

import java.util.ArrayList;
import java.util.List;



public class OneProducerOneConsumerDemo {

    public static void main(String[] args) {

        //一生产，一消费
        MyStack myStack = new MyStack();
        P p = new P(myStack);
        C c = new C(myStack);

        p_thread p_thread = new p_thread(p);
        p_thread.start();

        C_thread c_thread = new C_thread(c);
        c_thread.start();
    }
}

class MyStack {
    private final List<String> myList = new ArrayList<>();

    synchronized public void push() {
        try {
            if (myList.size() == 1) {
                this.wait();
            }
            myList.add("anyThing=" + Math.random());
            this.notify();
            System.out.println("push=" + myList.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public String pop() {
        String returnValue = "";
        try {
            if (myList.size() == 0) {
                System.out.println("pop 操作中的：" + Thread.currentThread().getName() + " 线程呈wait状态");
                this.wait();
            }
            returnValue = myList.get(0);
            myList.remove(0);
            this.notify();
            System.out.println("pop=" + myList.size());

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnValue;
    }
}


//案例1 一消费加一生产
class p_thread extends Thread {

    public P p;

    public p_thread(P p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true){
            p.pushService();
        }
    }
}

class C_thread extends Thread {

    public C c;

    public C_thread(C c) {
        this.c = c;
    }

    @Override
    public void run() {
        while (true){
            c.popService();
        }
    }
}

class P {
    private MyStack myStack;

    public P(MyStack myStack) {
        this.myStack = myStack;
    }

    public void pushService() {
        myStack.push();
    }
}

class C {
    private MyStack myStack;

    public C(MyStack myStack) {
        this.myStack = myStack;
    }

    public void popService() {
        System.out.println("pop="+myStack.pop());
    }
}


